package com.yinp.proapp.module.task.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewbinding.ViewBinding;

import com.yinp.proapp.adapter.ComViewHolder;
import com.yinp.proapp.adapter.CommonAdapter;
import com.yinp.proapp.adapter.SingleViewHolder;
import com.yinp.proapp.base.fragment.AppBaseFragment;
import com.yinp.proapp.constant.Constant;
import com.yinp.proapp.databinding.DialogTipBinding;
import com.yinp.proapp.databinding.FragmentToDoCurBinding;
import com.yinp.proapp.databinding.ItemTodayUndeterminedListBinding;
import com.yinp.proapp.greendao.DealLocaleTask;
import com.yinp.proapp.module.task.activity.AddUndeterminedActivity;
import com.yinp.proapp.module.task.bean.LocaleTaskBean;
import com.yinp.tools.fragment_dialog.BaseDialogFragment;
import com.yinp.tools.fragment_dialog.CommonDialogFragment;
import com.yinp.tools.fragment_dialog.DialogFragmentHolder;
import com.yinp.tools.fragment_dialog.ViewConvertListener;

import java.util.ArrayList;
import java.util.List;

/**
 * @author :yinpeng
 * date      :2021/9/2
 * package   :com.yinp.proapp.module.task.fragment
 * describe  :今日待做
 * 这种viewPager2+fragment不会触发onHiddenChanged和setUserVisibleHint
 * 会触发onResume和onPause
 */
public class ToDoCurFragment extends AppBaseFragment<FragmentToDoCurBinding> {
    private CommonAdapter<LocaleTaskBean> adapter;
    private List<LocaleTaskBean> dataList = new ArrayList<>();
    private DealLocaleTask<LocaleTaskBean> dealLocaleTask;

    private static final String UPDATE_TASK = "update_task";
    private static final String DELETE_TASK = "delete_task";

    public static ToDoCurFragment getInstance() {
        ToDoCurFragment toDoCurFragment = new ToDoCurFragment();
        Bundle bundle = new Bundle();
        toDoCurFragment.setArguments(bundle);
        return toDoCurFragment;
    }

    @Override
    protected void initViews(View view) {
        initClick(this, bd.noData, bd.noTips);
        bd.noTips.setText("暂无待做任务，点击添加");
        dealLocaleTask = new DealLocaleTask<>();
        initRecycler();
        getDataList();
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        if (bd.noData == v || bd.noTips == v) {
            goToActivity(AddUndeterminedActivity.class, Constant.REQUEST_CODE);
        }
    }

    private void initRecycler() {
        adapter = new CommonAdapter<LocaleTaskBean>(getContext(),dataList) {
            @Override
            protected SingleViewHolder setComViewHolder(View view, int viewType, ViewGroup parent) {
                ItemTodayUndeterminedListBinding binding = ItemTodayUndeterminedListBinding.inflate(mInflater, parent, false);
                return new SingleViewHolder(binding);
            }

            @Override
            public void onBindItem(SingleViewHolder holder, int position, LocaleTaskBean item) {
                ItemTodayUndeterminedListBinding binding = (ItemTodayUndeterminedListBinding) holder.getBinding();
                if (!TextUtils.isEmpty(item.getTitle())) {
                    binding.tvTitle.setText(item.getTitle());
                    binding.tvTitle.setVisibility(View.VISIBLE);
                }
                binding.tvContent.setText(item.getContent());
                binding.stvFinish.setOnClickListener(v -> {
                    saveDialog("确定完成当前任务吗？", holder.getAbsoluteAdapterPosition(), UPDATE_TASK);
                });
                binding.tvDelete.setOnClickListener(v -> {
                    saveDialog("确定删除当前任务吗？", holder.getAbsoluteAdapterPosition(), DELETE_TASK);
                });
            }
        };
        LinearLayoutManager llm = new LinearLayoutManager(getContext());
        bd.rvList.setLayoutManager(llm);
        //添加了这个，如果从最后开始删除就没有问题，如果随意删除就会崩溃
//        adapter.setHasStableIds(true);
        bd.rvList.setAdapter(adapter);
        bd.rvList.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                if (linearLayoutManager == null) {
                    linearLayoutManager = (LinearLayoutManager) recyclerView.getLayoutManager();
                }
                if (linearLayoutManager == null) {
                    return;
                }
                totalCount = linearLayoutManager.getItemCount();
                visiblePosition = linearLayoutManager.findLastVisibleItemPosition();
                if (totalCount == 0 || visiblePosition == 0) {
                    return;
                }
                if (is && dy > 0 && totalCount % visiblePosition == 2) {
                    is = false;
                    page++;
                    getDataList();
                } else if (totalCount % visiblePosition != 2) {
                    is = true;
                }
            }
        });
    }

    private int totalCount = -1;
    private int visiblePosition = -1;
    private LinearLayoutManager linearLayoutManager;
    private boolean is = false;

    private int page = 1;

    /**
     * 供外部调用的方法来刷新
     */
    public void initDataList() {
        page = 1;
        getDataList();
    }

    /**
     * 获取今日数据列表
     */
    private void getDataList() {
        List<LocaleTaskBean> list = dealLocaleTask.queryCurDateNoFinishList(page);
        if (list != null && list.size() > 0) {
            if (page == 1) {
                dataList.clear();
            }
            dataList.addAll(list);
            adapter.notifyItemRangeInserted(dataList.size(), list.size());
            bd.noLl.setVisibility(View.GONE);
            bd.rvList.setVisibility(View.VISIBLE);
        } else {
            if (dataList.size() == 0) {
                bd.noLl.setVisibility(View.VISIBLE);
                bd.rvList.setVisibility(View.GONE);
            }
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == Constant.REQUEST_CODE) {
            if (resultCode == Constant.RESULT_CODE) {
                page = 1;
                getDataList();
            }
        }
    }

    /**
     * 点击完成和删除出现的问题
     *
     * @param position
     * @param type
     */
    private void initType(int position, String type) {
        LocaleTaskBean bean = dataList.get(position);
        switch (type) {
            case UPDATE_TASK:
                bean.setIsFinish(true);
                dealLocaleTask.update(bean);
                dataList.remove(position);
                adapter.notifyItemRemoved(position);
                if (dataList.size() <= 0) {
                    bd.noLl.setVisibility(View.VISIBLE);
                    bd.rvList.setVisibility(View.GONE);
                }
                break;
            case DELETE_TASK:
                dealLocaleTask.delete(bean);
                dataList.remove(position);
                adapter.notifyItemRemoved(position);
                if (dataList.size() <= 0) {
                    bd.noLl.setVisibility(View.VISIBLE);
                    bd.rvList.setVisibility(View.GONE);
                }
                break;
        }
    }

    private void saveDialog(String title, int position, String type) {
        CommonDialogFragment.newInstance().setLayout(DialogTipBinding.inflate(LayoutInflater.from(getContext()), null, false))
                .setViewConvertListener(new ViewConvertListener() {
                    @Override
                    public void convertView(DialogFragmentHolder holder, BaseDialogFragment dialogFragment, ViewBinding viewBinding) {
                        super.convertView(holder, dialogFragment, viewBinding);
                        DialogTipBinding binding = (DialogTipBinding) viewBinding;
                        binding.tvTitle.setText(title);
                        binding.tvLeft.setOnClickListener(v -> dialogFragment.dismiss());
                        binding.tvRight.setOnClickListener(v -> {
                            dialogFragment.dismiss();
                            initType(position, type);
                        });
                    }
                }).setAnimStyle(BaseDialogFragment.CENTER).setGravity(BaseDialogFragment.CENTER).setPercentSize(0.9f, 0).show(getChildFragmentManager());
    }

    static class LocaleTaskViewHolder extends ComViewHolder {
        ItemTodayUndeterminedListBinding binding;

        public LocaleTaskViewHolder(ItemTodayUndeterminedListBinding itemView) {
            super(itemView.getRoot());
            binding = itemView;
        }
    }
}
